package cn.tedu.weibo.Controller; 
 /*
 @Time: 2022/8/22 8:29
 @Author:GShuai
 @File:UserController.class
 @Software:IntelliJ IDEA
*/

import cn.tedu.weibo.eneity.User;
import cn.tedu.weibo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody User user) {
        User u = mapper.selectByUsername(user.getUsername());
        if (u != null) {
            return 2;
        }
        mapper.insert(user);
        return 1;
    }


    @RequestMapping("/login")
    public int login(@RequestBody User user, HttpServletResponse response, HttpSession session) {
        System.out.println("user = " + user);
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if(user.getPassword().equals(u.getPassword())) {

                //记住登录状态 Session
                session.setAttribute("user",u);

                //判断是否需要记住  Cookie
                if(user.getRem()){  //true 代表需要记住
                    // 创建Cookie对象并且 吧用户名和密码装进Cookie 导包javax.servlet
                    Cookie c1 = new Cookie("username",u.getUsername());
                    Cookie c2= new Cookie("password",u.getPassword());
                    //设置cookie保存时间
                    c1.setMaxAge(60*60*24*30);
                    //把Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);

                }
                return 1;
            }
            return 3;
        }
        return 2;
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        // 吧登录成功时保存的用户对象取出返回给客户端，如果没有登录u为null
        User u  =(User) session.getAttribute("user");
        return u;
    }

    @RequestMapping("/logout")
    public  void logout(HttpSession session){
        // 删除登录成功保存的用户对象
        session.removeAttribute("user");
    }
}
